#!/bin/bash
############
## 检查主机ssl证书过期时间还剩多少天
## eg: ssl_check <host> [<port>]
##        host 主机名
##        port 端口,默认443
############
host=$1
port=$2
if [ -z "$port" ]; then
    port=443
fi
OPENSSL=/usr/bin/openssl
endDate=`$OPENSSL s_client -servername $host -host $host -port $port -showcerts </dev/null 2>/dev/null |
    sed -n '/BEGIN CERTIFICATE/,/END CERT/p' |
    $OPENSSL x509 -text 2>/dev/null |
    sed -n 's/ *Not After : *//p'`

if [ -n "$endDate" ]; then
    endDateSeconds=`date +%s --date "$endDate"`
    nowSeconds=`date +%s`
    echo $((($endDateSeconds-$nowSeconds)/86400))
else
    echo -1
fi
